package epam.car.rent.web.tags;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import dataAccess.DbWriter;

import epam.car.rent.Car;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Custom tag that outputs a list of cars
 * @author Alexander Tretyak
 *
 */
public class ListCars extends TagSupport {

    private static final Logger log = Logger.getLogger("carrentlogger");

    @SuppressWarnings("deprecation")
	@Override
    public int doStartTag() throws JspException {
    	ArrayList<Car> cars = new ArrayList<Car>();
    	
    	HttpSession session = (HttpSession) pageContext.getSession();


    	JspWriter w = pageContext.getOut();
		cars = DbWriter.getFreeCars();

		// w.write("Found: "+cars.size()+" records<br />");
		try {
			w.write("<table id=\"avalcars\">");
			
			String caption = "<tr style=\"border-bottom:1px solid #000000;\"><td>ID</td><td>"
				+session.getValue("layout.cars.model")
				+"</td><td>"+
				session.getValue("layout.cars.price")+"</td><td>"+
				session.getValue("layout.cars.type")+"</td><td>"+
				session.getValue("layout.cars.damages")+"</td><td>&nbsp;</td><td>&nbsp;</td></tr>";
			
			w.write(caption);
			
			for(Car c : cars){
				w.write("<tr><td>"+c.getId()
						+"</td><td>"+c.getModel()+"</td><td>"
						+c.getPrice()+"</td><td>"
						+c.getCarType()+"</td><td>"
						+c.getDamages()+"</td><td>"
						
						+"</td><td>"
						
						+"<a href=\"/RentCar?carId="+ c.getId() 
						+ "&clientId="+ session.getAttribute("clientID")+"\">"
						+session.getValue("layout.cars.rentIt")+"</a>"
						+"</td></tr>");
			}
			w.write("</table>");
		} catch (IOException e) {
			log.debug(e.getMessage());
		}
        return SKIP_BODY;

    }

    @Override
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }
}
